package com.promise.jokerdream.work.team.sect

import com.promise.jokerdream.database.entity.SectTournamentGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import kotlinx.coroutines.delay

// 门派邀请赛工作
class SectTournamentWork(
    private val config: SectTournamentGameConfigEntity,
    override val uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override val name: String
        get() = "门派邀请赛"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询门派邀请赛状态
            val queryResult = gameApi.querySectTournament()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 检查是否已组队
                    if (response.inGroup == 0) {
                        // 未组队，先报名
                        val signupResult = gameApi.signupSectTournament()
                        signupResult.foldWithApiException(
                            onSuccess = { signupResponse ->
                                historyManager.addHistory(name, signupResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                        
                        // 如果好友列表不为空，则邀请好友
                        val friendList = if (config.friendList.isEmpty()) emptyList() else config.friendList.split(",").map { it.trim() }
                        if (friendList.isNotEmpty()) {
                            friendList.forEach { friendUin ->
                                val inviteResult = gameApi.inviteSectTournamentFriend(friendUin)
                                inviteResult.foldWithApiException(
                                    onSuccess = { inviteResponse ->
                                        historyManager.addHistory(name, inviteResponse.getDescription())
                                    },
                                    onFailure = { code, msg ->
                                        historyManager.addHistory(name, msg, code)
                                    }
                                )
                                // 添加延迟避免请求过于频繁
                                delay(1000)
                            }
                        }
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}